from common_import import *

import os
import csv

plt.rcParams["font.sans-serif"] = ["SimHei"]  # 使用黑体
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题


def show_or_print(file_name=None):
    dir_path = "c:/Users/16028/Desktop/mcm/2024_4/proj/picture"
    if file_name:
        file_path = os.path.join(dir_path, file_name)
        plt.savefig(file_path, bbox_inches="tight", dpi=300)
    else:
        plt.show()
    plt.close("all")


def plot_predictions(y_test, y_pred, file_name=None):
    plt.figure(figsize=(10, 6))

    # 绘制预测值与实际值
    plt.scatter(y_test, y_pred, label="预测值", color="blue", alpha=0.6)

    # 绘制 y_test = y_pred 的参考线
    plt.plot(y_test, y_test, color="red", linestyle="--", label="y_test = y_pred")

    # 设置坐标轴刻度相同
    min_value = min(min(y_test), min(y_pred)) - 0.2
    max_value = max(max(y_test), max(y_pred)) + 0.2
    plt.xlim(min_value, max_value)
    plt.ylim(min_value, max_value)

    # 添加标签和标题
    plt.xlabel("实际值")
    plt.ylabel("预测值")
    plt.title("")
    plt.legend()
    plt.grid()
    if file_name:
        show_or_print(file_name)
    else:
        plt.show()


def get_np(filename):
    folder_path = "c:/Users/16028/Desktop/mcm/2024_4/proj/data"
    file_path = os.path.join(folder_path, filename)
    try:
        df = pd.read_csv(file_path)
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found in the specified directory.")
        return None

    column_names = df.columns
    dtype_mapping = {
        "int64": "i8",  # 64位整数
        "float64": "f8",  # 64位浮点数
        "object": "U370",  # 字符串，假设最大长度为367个字符
    }
    dtype = [(name, dtype_mapping[str(df[name].dtype)]) for name in column_names]
    structured_array = np.array([tuple(row) for row in df.to_numpy()], dtype=dtype)
    return structured_array


def get_csv(data, filename):  # 输入numpy数组 存储csv文件中
    folder_path = "c:/Users/16028/Desktop/mcm/2024_4/proj/data"
    file_path = os.path.join(folder_path, filename)
    with open(
        file_path,
        mode="w",
        newline="",
        encoding="utf-8",
    ) as file:
        writer = csv.writer(file)
        writer.writerow(data.dtype.names)
        for row in data:
            # formatted_row = [f"{x:.4f}" if isinstance(x, float) else x for x in row]
            formatted_row = row
            writer.writerow(formatted_row)


def xlsx_to_csv(xlsx_file):
    # 创建输出目录（如果不存在）
    output_dir = "c:/Users/16028/Desktop/mcm/2024_4/proj/data"
    file_path = os.path.join(output_dir, xlsx_file)
    # 读取 Excel 文件
    xls = pd.ExcelFile(file_path)
    # 遍历每个子表
    for sheet_name in xls.sheet_names:
        # 读取子表数据
        df = pd.read_excel(xls, sheet_name=sheet_name)
        # 处理空值（例如，替换为空字符串）
        df.fillna("", inplace=True)
        # 保存为 CSV 文件
        csv_file = os.path.join(
            output_dir, f"{xlsx_file.replace('.xlsx', '')}_{sheet_name}.csv"
        )
        df.to_csv(csv_file, index=False, encoding="utf-8")


if __name__ == "__main__":
    pass
    xlsx_to_csv("ADMET.xlsx")
